﻿Public Module ModuleTypeSystem

    Public Function GenericCast(Of U, V)(ByVal obj As U) As V
        Try
            Return CType(DirectCast(obj, Object), V)
        Catch ex As InvalidCastException
#If WINDOWS_PHONE Then
            Throw ex
#Else
            Return DirectCast(CompilerServices.Conversions.ChangeType(obj, GetType(V)), V)
#End If
        End Try
    End Function

    Public Function [Default](Of T)() As Object
        Dim typ = GetType(T)
        If typ.IsValueType Then
            Return 0
        Else
            Return Nothing
        End If
    End Function

    Public Function BytesToString(ByVal data() As Byte) As String
        Return BitConverter.ToString(data)
    End Function

    Public Function StringToBytes(ByVal data As String) As Byte()
        Dim elements() As String = data.Split("-")
        Dim lst As New List(Of Byte)
        For Each item In elements
            Dim value As Byte = 0
            For i As Integer = 0 To item.Length - 1
                Dim v As Integer = 0
                Dim a As Byte = AscW(item.Chars(i))
                If a >= AscW("0") And a <= AscW("9") Then
                    v = a - AscW("0")
                Else
                    v = a - AscW("A") + 10
                End If
                value += v * Math.Pow(16, item.Length - i - 1)
            Next i
            lst.Add(value)
        Next item
        Return lst.ToArray()
    End Function

End Module